/**
 * 	 Copyright (c) 2008, 2009 Lukas Zaruba
 * 
 *   This file is part of UniAnalyzer (Universal Analyzer).
 *
 *   UniAnalyzer is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   UniAnalyzer is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with UniAnalyzer. If not, see <http://www.gnu.org/licenses/>.
 */

package net.zarubsys.unianalyzer.dataviews.lpt.gui.conf.runWizard;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;

import net.zarubsys.unianalyzer.dataminers.lpt.exceptions.AnalysisException;
import net.zarubsys.unianalyzer.dataminers.lpt.gui.parameterObject.LPTMeasuringSettings;
import net.zarubsys.unianalyzer.dataminers.lpt.internal.impl.LptDataMiner;
import net.zarubsys.unianalyzer.dataminers.lpt.results.IResult;
import net.zarubsys.unianalyzer.dataminers.lpt.wizard.utils.ParameterObjectParser;

import org.apache.log4j.Logger;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWizard;
import org.eclipse.ui.dialogs.WizardNewFileCreationPage;

/**
 * RunWizard
 *
 * @author  &lt;A HREF=&quot;mailto:lukas.zaruba@media-solutions.cz&quot;&gt;Lukas Zaruba&lt;/A&gt;, MEDIA SOLUTIONS CZECH REPUBLIC Ltd.
 * @version $Revision$ $Date$
 */
public class RunWizard extends Wizard implements IWorkbenchWizard {

	private WizardNewFileCreationPage fileSelectionPage;
	private IStructuredSelection selection;
	
	private static final Logger log = Logger.getLogger(RunWizard.class);
	
	public RunWizard() {
		super();
		setWindowTitle("LPT measuring");
		setNeedsProgressMonitor(true);
	}
	
	@Override
	public void addPages() {
		fileSelectionPage = new WizardNewFileCreationPage("fileSelect", selection);
		fileSelectionPage.setTitle("Select destination");
		fileSelectionPage.setDescription("Select destination where result of measuring will be saved.");
		fileSelectionPage.setFileExtension("lpt");
		addPage(fileSelectionPage);
	}

	@Override
	public boolean performFinish() {
		final IFile targetFile = fileSelectionPage.createNewFile();
		IRunnableWithProgress op = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					monitor.beginTask("Saving measuring settings...", -1);
					doFinish(targetFile, monitor);
				} catch (AnalysisException e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
		};
		try {
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			return false;
		} catch (InvocationTargetException e) {
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		return true;
	}
	
	private void doFinish(IFile targetFile, IProgressMonitor monitor) throws AnalysisException {
		monitor.subTask("Getting measuring settings...");
		File sourceFile = ((IResource) selection.getFirstElement()).getRawLocation().toFile();
		LPTMeasuringSettings measuringSettings = getMeasuringSettings(sourceFile);
		IResult result;
		monitor.subTask("Reading data from port...");
		result = LptDataMiner.getInstance().analyze(new ParameterObjectParser(measuringSettings));
		
		monitor.subTask("Saving result...");
		
		ObjectOutputStream os = null;
		try {
			os = new ObjectOutputStream(new FileOutputStream(targetFile.getRawLocation().toFile()));
			os.writeObject(result);
		} catch (FileNotFoundException e) {
			log.error("Error while saving measuring result.", e);
		} catch (IOException e) {
			log.error("Error while saving measuring result.", e);
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				log.error("Error while closing output stream of measuring result.", e);
			}
		}
	}
	
	private LPTMeasuringSettings getMeasuringSettings(File file) {
		ObjectInputStream ois = null;
		LPTMeasuringSettings result = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(file));
			result = (LPTMeasuringSettings) ois.readObject();
		} catch (FileNotFoundException e) {
			log.error("Error reading measuring result.", e);
		} catch (IOException e) {
			log.error("Error reading measuring result.", e);
		} catch (ClassNotFoundException e) {
			log.error("Error reading measuring result.", e);
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					log.error("Error closing measuring settings input stream.", e);
				}
			}
		}
		return result;
	}
	
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}

}


/*
 * $Log$
 */